package cn.kgc.jdbc.dao;

import cn.kgc.jdbc.entity.Student;
import cn.kgc.jdbc.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/4/22
 * 学生数据持久化层的实现类 写具体的实现方法
 */
public class StudentDaoImpl  implements  StudentDao {

    //添加学生
    @Override
    public int insertStudent(String stuName) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "insert into student(stu_name)values(?)";
        try {
            int update = queryRunner.update(sql, stuName);
            return  update;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int delStudent(int id) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "delete from student where id = ?";
        try {
            int line = queryRunner.update(sql, id);
            return  line;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public int updateStudent(int stuNo, long clazzId) {
        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "update student set class_id = ? where id = ?";
        try {
            int line = queryRunner.update(sql, clazzId,stuNo);
            return  line;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return 0;
    }

    @Override
    public List<Student> selectAll() {

        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "select student.id , stu_name AS stuName , class_id AS classId , class_name AS className " +
                "from student left join clazz on student.class_id = clazz.id ";
        try {
            List<Student> students = queryRunner.query(sql, new BeanListHandler<>(Student.class));
            return students;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public Student selectByName(String stuName) {

        QueryRunner queryRunner = new QueryRunner(DruidUtil.getDataSource());
        String sql = "select id,stu_name as stuName ,class_id as classId from student where stu_name = ?";
        try {
            Student student = queryRunner.query(sql, new BeanHandler<>(Student.class),stuName);
            return  student;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }


}
